//
//  RegisterViewController.m
//  17Login
//
//  Created by 建 任 on 13-4-2.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//

#import "RigisterViewController.h"
#import "Utility.h"
#import "Config.h"
#import "DefineAction.h"
#import "JSON.h"
#import "AppDelegate.h"



@implementation RegisterViewController


-(void) viewDidLoad
{
    [super viewDidLoad];
    //设置背景
    self.view.backgroundColor = [[UIColor alloc] initWithRed:123.0/255.0 green:123.0/255.0 blue:123.0/255.0 alpha:100];
    
    //邮箱
    UIImageView *imageViewEmail=[[UIImageView alloc] initWithImage:[Utility imageNamed:@"login_fextfield_bg.png"]];
    imageViewEmail.frame=CGRectMake(35, 40, 250, 36);
    [self.view addSubview:imageViewEmail];
    self.emailField = [self customTextField:CGRectMake(40, 40, 240, 36)];
    self.emailField.placeholder = @"用邮箱地址作为用户名";
    self.emailField.delegate=self;
    self.emailField.keyboardType=UIKeyboardTypeEmailAddress;
    [self.view addSubview:self.emailField];
    
    //昵称
    UIImageView *imageViewnickField=[[UIImageView alloc] initWithImage:[Utility imageNamed:@"login_fextfield_bg.png"]];
    imageViewnickField.frame=CGRectMake(35, 85, 250, 36);
    [self.view addSubview:imageViewnickField];
    self.nickField = [self customTextField:CGRectMake(40, 85, 240, 36)];
    self.nickField.placeholder = @"您的昵称";
    self.nickField.delegate=self;
    [self.view addSubview:self.nickField];
    
    //密码
    UIImageView *imageViewpassword=[[UIImageView alloc] initWithImage:[Utility imageNamed:@"login_fextfield_bg.png"]];
    imageViewpassword.frame=CGRectMake(35, 130, 250, 36);
    [self.view addSubview:imageViewpassword];
    self.pwdField = [self customTextField:CGRectMake(40, 130, 240, 36)];
    self.pwdField.placeholder = @"设置密码";
    self.pwdField.delegate=self;
    self.pwdField.secureTextEntry = YES;
    [self.view addSubview:self.pwdField];
    
    //重复密码
    UIImageView *imageViewpassword2=[[UIImageView alloc] initWithImage:[Utility imageNamed:@"login_fextfield_bg.png"]];
    imageViewpassword2.frame=CGRectMake(35, 175, 250, 36);
    [self.view addSubview:imageViewpassword2];
    self.pwd2Field = [self customTextField:CGRectMake(40, 175, 240, 36)];
    self.pwd2Field.placeholder = @"重复密码";
    self.pwd2Field.delegate=self;
    self.pwd2Field.secureTextEntry = YES;
    self.pwd2Field.returnKeyType=UIReturnKeySend;
    [self.view addSubview:self.pwd2Field];
    
    
    //完成
    [self.view addSubview:[Utility customButton:self action:@selector(goRegAction:) normalImage:@"registerSub1.png" lightedImage:@"registerSub2.png" frame:CGRectMake(35, 240, 250, 40) title:nil tag:20]];
    
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField==self.emailField) {
        CGRect rect=self.view.frame;
        rect.origin.y=-20;
        self.view.frame=rect;
        [self.emailField becomeFirstResponder];
    }else if(textField==self.nickField) {
        CGRect rect=self.view.frame;
        rect.origin.y=-40;
        self.view.frame=rect;
        [self.nickField becomeFirstResponder];
    }if(textField==self.pwdField) {
        CGRect rect=self.view.frame;
        rect.origin.y=-60;
        self.view.frame=rect;
        [self.pwdField becomeFirstResponder];
    }if(textField==self.pwd2Field) {
        CGRect rect=self.view.frame;
        rect.origin.y=-80;
        self.view.frame=rect;
        [self.pwd2Field becomeFirstResponder];
    }
    
}

-(IBAction)goRegAction:(id)sender{
    NSString *username=self.emailField.text;
    NSString *nickname=self.nickField.text;
    NSString *password=self.pwdField.text;
    NSString *passwordsure=self.pwd2Field.text;
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    if (username==nil||[username isEqualToString:@""]) {
        [Utility customAlertWithMsg:USERNAMEMSG1 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    if (![Utility ValidateEmail:username]) {
        [Utility customAlertWithMsg:USERNAMEMSG2 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    if (nickname==nil||[nickname isEqualToString:@""]) {
        [Utility customAlertWithMsg:NICKNAMESG1 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    
	if (password==nil||[password isEqualToString:@""]||[password length]<6) {
        [Utility customAlertWithMsg:PASSWORDMSG1 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    if (![password isEqualToString:passwordsure]) {
        [Utility customAlertWithMsg:PASSWORDMSG2 andTitle:ALRRTTITLE andDelagate:nil];
        return;
	}
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility getServerUrl],REGACTION];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                            username,@"u.u1",
                                            nickname,@"u.u2",
                                            password,@"u.u3",
                                            0,@"type",
                                            nil]
        andFile:nil];
    [self.request startLoadData];

}
- (void)requestFinished:(id)context{
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result  objectForKey:@"code"] integerValue]==0) {
            NSDictionary *userdict=[result objectForKey:@"data"];
            if (userdict) {
                NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
                [user setObject:[userdict objectForKey:@"u0"] forKey:USERID];
                [user setObject:[userdict objectForKey:@"u1"] forKey:USERNAME];
                [user setObject:[userdict objectForKey:@"u2"] forKey:USERNICKNAME];
                [user setObject:self.pwdField.text forKey:USERPASSWORD];
                [user setObject:[userdict objectForKey:@"u6"] forKey:USERLOGO];
                [user setObject:[userdict objectForKey:@"u7"] forKey:USERINTRO];
                [user synchronize];
                AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
                [app popLoginViewController];
            }else{
             [Utility customAlertWithMsg:LOGINFAIL andTitle:ALRRTTITLE andDelagate:nil];
            }
           
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:LOGINFAIL andTitle:NETWORTERROE andDelagate:nil];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.emailField) {
        CGRect rect=self.view.frame;
        rect.origin.y=-20;
        self.view.frame=rect;
        [self.nickField becomeFirstResponder];
    }else if(textField==self.nickField) {
        CGRect rect=self.view.frame;
        rect.origin.y=-40;
        self.view.frame=rect;
        [self.pwdField becomeFirstResponder];
    }if(textField==self.pwdField) {
        CGRect rect=self.view.frame;
        rect.origin.y=-60;
        self.view.frame=rect;
          [self.pwd2Field becomeFirstResponder];
    }else if(textField==self.pwd2Field) {
        CGRect rect=self.view.frame;
        rect.origin.y=0;
        self.view.frame=rect;
        [self.emailField resignFirstResponder];
        [self.nickField resignFirstResponder];
        [self. pwdField resignFirstResponder];
        [self.pwd2Field resignFirstResponder];
        [self goRegAction:nil];
    }
    return NO;
}

-(UITextField*) customTextField:(CGRect) frame{

    UITextField *textFied = [[UITextField alloc] initWithFrame:frame];
    textFied.autocorrectionType = UITextAutocorrectionTypeNo;
    textFied.returnKeyType=UIReturnKeyNext;
    textFied.clearButtonMode=UITextFieldViewModeWhileEditing;
    textFied.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    textFied.backgroundColor=[UIColor  clearColor];
    textFied.borderStyle=UITextBorderStyleNone;
    textFied.textColor=[UIColor blackColor];
    textFied.font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    textFied.autocorrectionType=UITextAutocorrectionTypeNo;
    [textFied setBorderStyle:UITextBorderStyleNone];
    textFied.keyboardType=UIKeyboardTypeDefault;
    return textFied;
}

-(void) viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end


